import requests

# 获取Access token的URL和参数
TOKEN_URL = 'https://open.xjguoyu.cn/api/auth/oauth/token'
CLIENT_ID = '6d9ed85e9826e6de8b6a39cea81bba86'
CLIENT_SECRET = 'xYXYcMmBeTDRGa6HQwPpRCieTfzbKcDZ'
GRANT_TYPE = 'client_credentials'

# 获取Access token
token_params = {
    'grant_type': GRANT_TYPE,
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET
}
token_response = requests.post(TOKEN_URL, data=token_params)
access_token = token_response.json().get('access_token')

# 检查是否成功获取Access token
if not access_token:
    print("Failed to get access token")
else:
    print("Access token obtained")

# APP KEY
APP_KEY = 'ldxlVOlPTkF5qyKKNZxkkiBgu2qkFh47'

# 机器翻译API的URL
MT_API_URL = 'https://open.xjguoyu.cn/api/core/1.0/mt'

# 翻译请求的头部
headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/x-www-form-urlencoded'
}

# 翻译请求的参数
params = {
    'app_key': APP_KEY,
    'source': 'cn',  # 源语言代码，'cn'为汉语
    'target': 'ug',  # 目标语言代码，'ug'为维吾尔语
    'q': '你好，你好吗？'  # 要翻译的文本
}

# 发送POST请求进行翻译
response = requests.post(MT_API_URL, headers=headers, data=params)

# 检查响应状态并打印结果
if response.status_code == 200:
    response_json = response.json()
    if 'data' in response_json and 'dst' in response_json['data']:
        translated_text = response_json['data']['dst']
        print(f'Translated text: {translated_text}')
    else:
        print('Translation failed')
else:
    print(f'Error: {response.text}')